import {iResumeRecord} from "./resume.utils";
import {deepcopy} from "@peryl/utils/deepcopy";
import {http} from "../../modules/plain-design/http";
import {$notice} from "plain-design";
import {PlainCmsNamespace} from "@peryl/react-cms-editor";

export async function saveResume(
  {
    onStart,
    onFinally,
    onError,
    onSuccess,
    image,
    dataMetas,
    sourceResumeRecord,
    isTemplate
  }: {
    onStart?: () => void,
    onFinally?: () => void,
    onError?: (e?: any) => void,
    onSuccess?: (newResumeRecord: iResumeRecord) => void,
    image: string,
    dataMetas: PlainCmsNamespace.iDataMeta[],
    sourceResumeRecord: iResumeRecord | null | undefined,
    isTemplate: 'Y' | 'N'
  }
) {
  onStart?.();
  try {
    const resumeRecord: iResumeRecord = {
      ...deepcopy(sourceResumeRecord),
      jsonString: JSON.stringify(dataMetas),
      image,
      isTemplate
    };
    const respData = await http.post<{ result: iResumeRecord }>(`resume/${resumeRecord.id ? 'update' : 'insert'}`, { row: resumeRecord });
    if (!!respData.result.id) {
      $notice.success('保存成功!');
      onSuccess?.(respData.result);
    } else {
      $notice.success('保存失败!');
      onError?.();
    }
  } catch (e: any) {
    if (!e) {return;}
    console.error(e);
    onError?.(e);
    $notice.error(e.message || JSON.stringify(e));
  } finally {
    onFinally?.();
  }
}
